package com.ruoyi.question.util;

import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.stream.StreamSource;
import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

public class OmmlUtils {

    /**
     * 将word文档中公式格式为omML转换为mathMl
     * @param omML
     * @return
     */
    public static String getMathMLFromNode(String omML) {
        //通过word中的xsl转成器解析omml公式格式
        StreamSource xslSource = new StreamSource(new File("src/main/resources/OMML2MML.XSL"));
        StringWriter writer = new StringWriter();
        try {
            Transformer t = TransformerFactory.newInstance().newTransformer(xslSource);
            Source sources = new StreamSource(new StringReader(omML));
            StreamResult result = new StreamResult(writer);
            t.transform(sources, result);
        } catch (TransformerException e) {
            e.printStackTrace();
        }
        String mathML = writer.getBuffer().toString();
        mathML = mathML.replaceAll("xmlns:m=\"http://schemas.openxmlformats.org/officeDocument/2006/math\"", "");
        mathML = mathML.replaceAll("xmlns:mml", "xmlns");
        mathML = mathML.replaceAll("mml:", "");
        return mathML;
    }
}
